package com.lmb.aspect;

import com.lmb.annotation.LogMethod;
import com.lmb.bean.SysOperLog;
import com.lmb.service.SysOperLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MemberSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;

@Component
@Aspect
public class EasyAspect {
    @Autowired
    private SysOperLogService sysOperLogService;

    @Pointcut("@annotation(com.lmb.annotation.LogMethod)")
    public void logmethod(){}

    @Around("logmethod() && @annotation(logMethod)")
    public Object recordLog(ProceedingJoinPoint point, LogMethod logMethod) throws Throwable {
        Object obj = null;
        StringBuilder strb = new StringBuilder();
        String serviceName = logMethod.serviceName();
        boolean decordParam = logMethod.recordParam();
        boolean decordReturn = logMethod.recordReturn();

        MemberSignature memberSignature = (MemberSignature) point.getSignature();
        String methodName = memberSignature.getName();

        strb.append("[").append(serviceName).append("]")
                .append("   method:").append(methodName)
                .append("   params:");

        // 只执行一次目标方法
        obj = point.proceed(); // 关键修复：合并为一次调用

        if (decordParam) {
            strb.append(Arrays.toString(point.getArgs()));
        }
        if (decordReturn) {
            strb.append("     return:").append(obj);
        }

        Date date = new Date();
        strb.append("   [").append(new java.text.SimpleDateFormat("YYYY-MM-dd  HH:mm:ss SSS").format(date)).append("]");
        System.out.println(strb.toString());

        SysOperLog log = new SysOperLog();
        log.setService_name(serviceName);
        log.setMethod_name(methodName);
        log.setParams(decordParam ? Arrays.toString(point.getArgs()) : null);
        log.setReturn_value(decordReturn ? obj.toString() : null);
        log.setCall_time(new java.sql.Timestamp(System.currentTimeMillis()));
        sysOperLogService.add(log);

        return obj;
    }
}
